package com.alibaba.citrus.cr.mn.order.center.forecastorder.ability;

import com.alibaba.citrus.cr.common.annotation.ProcessInvoker;
import com.alibaba.citrus.cr.mn.order.center.common.constants.ForecastConstants;
import com.alibaba.cloud.retail.policy.center.ability.PriceCalculateAbilityService;
import com.alibaba.cloud.retail.policy.center.dto.RecordCalculateRequestDTO;
import com.alibaba.cloud.retail.policy.center.dto.RecordCalculateRequestItemDTO;
import com.alibaba.cloud.retail.policy.center.enums.PriceFactorEnum;
import com.alibaba.cloud.retail.policy.center.model.PriceFactor;
import com.alibaba.cloud.retail.policy.center.resp.RecordCalculateResp;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crforecastsales.dto.request.QueryGoodsDetailRequest;
import com.epoch.app.crforecastsales.model.dto.GiftSDO;
import com.epoch.app.crforecastsales.model.dto.SubOrderInfo;
import com.epoch.app.crforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.crforecastsales.sdo.MainOrderInfo;
import com.epoch.app.crplatformenhance.domain.customersalescope.dto.BatchQueryByCustomerCodesRequest;
import com.epoch.app.crplatformenhance.domain.customersalescope.model.CustomerSaleScope;
import com.epoch.app.crplatformenhance.domain.customersalescope.service.CustomerSaleScopeService;
import com.epoch.app.crpricecenter.api.activityquery.service.ActivityQueryService;
import com.epoch.app.crpricecenter.api.pricequery.service.PriceQueryService;
import com.epoch.app.crpricecenter.dto.request.*;
import com.epoch.app.crpricecenter.dto.response.ItemPriceResponse;
import com.epoch.app.crpricecenter.dto.response.PriceQueryResponse;
import com.epoch.app.crpricecenter.model.dto.ActivityResponse;
import com.epoch.app.crpricecenter.model.dto.QueryActivityRequest;
import com.epoch.app.mnordercenter.model.dto.PolicyPriceMainRequest;
import com.epoch.app.mnordercenter.model.dto.PolicyPriceQueryRequest;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: qiaojiange
 * @create: 2021/12/10
 * @Description 请描述类的业务用途
 */
@Component
public class NormalPriceQueryUtils {

    private static Log log = Log.getLogger(NormalPriceQueryUtils.class);

    /**
     * 内外码转换 key
     */
    private static String CODE_FLAG = "codeFlag";
    /**
     * 内外码转换 value
     */
    private static String INNER_CODE_TO_OUT_CODE = "inner_code_to_out_code";

    @Resource
    private PriceQueryService priceQueryService;
    @Resource
    private CustomerSaleScopeService customerSaleScopeService;
    @Resource
    private ActivityQueryService activityQueryService;
    @DubboReference
    private PriceCalculateAbilityService priceCalculateAbilityService;

    @ProcessInvoker(printLog = true)
    public List<PolicyPriceQueryRequest> queryPolicyPrice(PolicyPriceMainRequest request) {

        if (CollectionUtils.isEmpty(request.getCalculateItemList())) {
            return Lists.newArrayList();
        }

        List<PolicyPriceQueryRequest> orderLinePriceQuery = request.getCalculateItemList();
        ArrayList<RecordCalculateRequestItemDTO> calculateItemList = new ArrayList<>();

        for (PolicyPriceQueryRequest subOrderInfo : orderLinePriceQuery) {

            RecordCalculateRequestItemDTO recordCalculateReqItem = new RecordCalculateRequestItemDTO();

            recordCalculateReqItem.setPriceTypeCode(subOrderInfo.getPriceTypeCode());
            Date now = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(now);
            recordCalculateReqItem.setQueryDate(format);
            ArrayList<PriceFactor> priceFactors = new ArrayList<>();
            recordCalculateReqItem.setPriceFactors(priceFactors);

            if (StringUtils.isNotBlank(subOrderInfo.getMaterialCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.MATERIAL_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getMaterialCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getScItemGroupCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.SC_ITEM_GROUP_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getScItemGroupCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getCustomerCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.CUSTOMER_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getCustomerCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getCustomerSaleAddressCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.CUSTOMER_SALE_ADDRESS_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getCustomerSaleAddressCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getCustomerSendAddressCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.CUSTOMER_SEND_ADDRESS_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getCustomerSendAddressCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getChannelCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.CHANNEL_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getChannelCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getDepartmentCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.DEPARTMENT_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getDepartmentCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getSalesUnitCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.SALES_UNIT_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getSalesUnitCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getOrgSalesOrganizationCode())) {
                PriceFactor priceFactor = new PriceFactor();
                priceFactor.setFactorCode(PriceFactorEnum.ORG_SALES_ORGANIZATION_CODE.getCode());
                priceFactor.setFactorValue(subOrderInfo.getOrgSalesOrganizationCode());
                priceFactors.add(priceFactor);
            }

            if (StringUtils.isNotBlank(subOrderInfo.getCustomerCode())) {
                try {
                    // 查询客户客户售达方信息
                    BatchQueryByCustomerCodesRequest customerSales = new BatchQueryByCustomerCodesRequest();
                    customerSales.setCustomerCodes(Collections.singletonList(subOrderInfo.getCustomerCode()));
                    Result<List<CustomerSaleScope>> listResult = customerSaleScopeService.batchQueryByCustomerCodes(customerSales);
                    if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                        CustomerSaleScope customerSaleScope = listResult.getResult().get(0);

                        if (StringUtils.isNotBlank(customerSaleScope.getCustomerGroup())) {
                            PriceFactor priceFactor = new PriceFactor();
                            priceFactor.setFactorCode(PriceFactorEnum.CUSTOMER_GROUP.getCode());
                            priceFactor.setFactorValue(customerSaleScope.getCustomerGroup());
                            priceFactors.add(priceFactor);
                        }
                        if (StringUtils.isNotBlank(customerSaleScope.getSalesArea())) {
                            PriceFactor priceFactor = new PriceFactor();
                            priceFactor.setFactorCode(PriceFactorEnum.SALES_AREA.getCode());
                            priceFactor.setFactorValue(customerSaleScope.getSalesArea());
                            priceFactors.add(priceFactor);
                        }
                    }
                } catch (Exception e) {
                    log.error("查询客户客户售达方错误 customerCode: {}", subOrderInfo.getCustomerCode());
                    log.error("查询客户客户售达方错误 error", e);
                }
            }
            calculateItemList.add(recordCalculateReqItem);
        }

        RecordCalculateRequestDTO calculateReq = new RecordCalculateRequestDTO();
        calculateReq.setCalculateItemList(calculateItemList);
        calculateReq.setBusinessType(request.getBusinessType());
        calculateReq.setFromSys(request.getFromSys());
        calculateReq.setSalesOrganizationCode(request.getSalesOrganizationCode());
        log.info("查询价格:{}", JSON.toJSONString(calculateReq));
        com.alibaba.lydass.bizphin.maca.model.Result<List<RecordCalculateResp>> listResult = priceCalculateAbilityService.priceCalculate(calculateReq);
        if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
            return orderLinePriceQuery;
        }

        List<RecordCalculateResp> result = listResult.getResult();
        Map<String, Double> itemPriceMap = result.stream().collect(HashMap::new, (m, v) -> m.put(v.getProductId() + "-" + v.getPriceUnit(), v.getMoneyAmount()), HashMap::putAll);
        log.info("价格匹配 itemPriceMap: {}", itemPriceMap);
        for (PolicyPriceQueryRequest orderLineQuery : orderLinePriceQuery) {
            log.info("价格匹配 orderLineQuery: {}", orderLineQuery);
            BigDecimal unitPrice = BigDecimal.valueOf(-9.9D);
            try {
                String key = orderLineQuery.getMaterialCode() + "-" + orderLineQuery.getSalesUnitCode();
                if (itemPriceMap.containsKey(key)) {
                    unitPrice = BigDecimal.valueOf(itemPriceMap.get(key));
                }
            } catch (Exception e) {
                log.error("价格匹配错误 error", e);
            }
            orderLineQuery.setUnitPrice(unitPrice.multiply(new BigDecimal("100")).longValue());
        }
        return orderLinePriceQuery;
    }

    @ProcessInvoker(printLog = true)
    public List<SubOrderInfo> queryGoodsDetail(QueryGoodsDetailRequest request) {
        MainOrderInfo forecastOrderSDO = request.getForecastOrderSDO();
        if (CollectionUtils.isEmpty(forecastOrderSDO.getForecastOrderLineSDOList())) {
            return Lists.newArrayList();
        }

        List<SubOrderInfo> forecastOrderLineSDOList = forecastOrderSDO.getForecastOrderLineSDOList();
        List<DimensionPropertyInfoRequest> dimensionPropertyInfoRequestList = new ArrayList<>();
        for (SubOrderInfo subOrderInfo : forecastOrderLineSDOList) {
            //转换参数
            String firstCategoryCode = null;
            String firstCategoryDesc = null;
            String secondCategoryCode = null;
            String secondCategoryDesc = null;

            if (StringUtils.isNotBlank(subOrderInfo.getIdPath())) {
                String[] categoryIds = subOrderInfo.getIdPath().split(">>");
                firstCategoryCode = categoryIds[0] == null ? null : categoryIds[0];
                if (categoryIds.length >= 2) {
                    secondCategoryCode = categoryIds[1] == null ? null : categoryIds[1];
                }
            }

            if (StringUtils.isNotBlank(subOrderInfo.getCurrentPath())) {
                String[] categoryDescList = subOrderInfo.getCurrentPath().split(">>");
                firstCategoryDesc = categoryDescList[0] == null ? null : categoryDescList[0];
                if (categoryDescList.length >= 2) {
                    secondCategoryDesc = categoryDescList[1] == null ? null : categoryDescList[1];
                }
            }

            subOrderInfo.setFirstCategoryCode(firstCategoryCode);
            subOrderInfo.setFirstCategoryDesc(firstCategoryDesc);
            subOrderInfo.setSecondCategoryCode(secondCategoryCode);
            subOrderInfo.setSecondCategoryDesc(secondCategoryDesc);

            DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
            dimensionPropertyInfoRequest.setPriceTypeId("ZP01");
            dimensionPropertyInfoRequest.setPriceUseDate(new Date());

            //货品组
            MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
            materialInfoRequest.setMaterialCode(subOrderInfo.getScItemId());
            materialInfoRequest.setScItemGroupCode(forecastOrderSDO.getProductGroupCode());

            HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
            humanInfoRequest.setCustomerCode(forecastOrderSDO.getCustomerCode());
            humanInfoRequest.setCustomerSendAddressCode(forecastOrderSDO.getReceiveAddressCode());
            humanInfoRequest.setCustomerSaleAddressCode(forecastOrderSDO.getCustomerCode());

            PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
            placeInfoRequest.setChannelCode(forecastOrderSDO.getChannelCode());
            placeInfoRequest.setDepartmentCode(forecastOrderSDO.getDepartmentCode());
            placeInfoRequest.setSalesUnitCode(subOrderInfo.getSaleUnitCode());
            placeInfoRequest.setOrgSalesOrganizationCode(request.getForecastOrderSDO().getOrganizationCode());

            if (StringUtils.isNotBlank(forecastOrderSDO.getCustomerCode())) {
                try {
                    // 查询客户客户售达方信息
                    BatchQueryByCustomerCodesRequest customerSales = new BatchQueryByCustomerCodesRequest();
                    customerSales.setCustomerCodes(Collections.singletonList(forecastOrderSDO.getCustomerCode()));
                    Result<List<CustomerSaleScope>> listResult = customerSaleScopeService.batchQueryByCustomerCodes(customerSales);
                    if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                        CustomerSaleScope customerSaleScope = listResult.getResult().get(0);
                        humanInfoRequest.setCustomerGroup(customerSaleScope.getCustomerGroup());
                        placeInfoRequest.setSalesArea(customerSaleScope.getSalesArea());
                    }
                } catch (Exception e) {
                    log.error("查询客户客户售达方错误 customerCode: {}", forecastOrderSDO.getCustomerCode());
                    log.error("查询客户客户售达方错误 error", e);
                }
            }

            dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
            dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
            dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);

            dimensionPropertyInfoRequestList.add(dimensionPropertyInfoRequest);
        }

        Map<String, String> features = new HashMap<>();
        features.put("codeFlag", "inner_code_to_out_code");
        PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
        priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoRequestList);
        priceQueryRequest.setFeatures(features);
        Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPriceExpand(priceQueryRequest);
        if (Objects.isNull(priceQueryResponseResult)
                || Objects.isNull(priceQueryResponseResult.getResult())
                || CollectionUtils.isEmpty(priceQueryResponseResult.getResult().getItemPriceResponseList())) {
            return forecastOrderLineSDOList;
        }

        PriceQueryResponse result = priceQueryResponseResult.getResult();
        Map<String, Long> itemPriceMap = result.getItemPriceResponseList().stream()
                .collect(HashMap::new, (m, v) -> m.put(v.getItemId() + "-" + v.getPriceUnit(), v.getMoneyAmout()), HashMap::putAll);
        for (SubOrderInfo forecastOrderLineSDO : forecastOrderLineSDOList) {
            Long unitPrice = itemPriceMap.getOrDefault(forecastOrderLineSDO.getScItemId() + "-" + forecastOrderLineSDO.getSaleUnitCode(), -999L);
            forecastOrderLineSDO.setUnitPrice(unitPrice);
        }

        return forecastOrderLineSDOList;
    }

    public Result<ActivityResponse> queryActivity(List<ActivityInfoRequest> activityInfoRequestList) {
        if (CollectionUtils.isEmpty(activityInfoRequestList)) {
            return Result.success(null);
        }
        QueryActivityRequest queryActivityRequest = new QueryActivityRequest();
        Map<String, String> features = new HashMap<>();
        features.put(ForecastConstants.CODE_FLAG, ForecastConstants.OUT_CODE_TO_INNER_CODE);
        queryActivityRequest.setFeatures(features);
        queryActivityRequest.setActivityInfoRequestList(activityInfoRequestList);
        return activityQueryService.batchQueryCanUsingActivityExpand(queryActivityRequest);
    }

    /**
     * 获取赠品价格
     *
     * @param forecastOrderSDO 主单信息
     * @param giftSDO          赠品信息
     * @return
     */
    @ProcessInvoker
    public Long obtainGiftPrice(ForecastOrderSDO forecastOrderSDO, GiftSDO giftSDO) {
        //一 获取价格
        PriceQueryRequest priceQueryRequest = new PriceQueryRequest();
        List<DimensionPropertyInfoRequest> dimensionPropertyInfoList = new ArrayList<>();
        DimensionPropertyInfoRequest dimensionPropertyInfoRequest = new DimensionPropertyInfoRequest();
        //价格类型
        dimensionPropertyInfoRequest.setPriceTypeId("ZP01");
        //价格使用时间
        dimensionPropertyInfoRequest.setPriceUseDate(new Date());


        PlaceInfoRequest placeInfoRequest = new PlaceInfoRequest();
        placeInfoRequest.setChannelCode(forecastOrderSDO.getChannelCode());
        placeInfoRequest.setDepartmentCode(forecastOrderSDO.getDepartmentCode());
        placeInfoRequest.setSalesUnitCode(giftSDO.getGiftSalesUnitCode());
        placeInfoRequest.setOrgSalesOrganizationCode(forecastOrderSDO.getOrganizationCode());


        //货的信息
        MaterialInfoRequest materialInfoRequest = new MaterialInfoRequest();
        //货品编码（ SAP物料编码）
        materialInfoRequest.setMaterialCode(giftSDO.getScItemId());
        //产品组编码 货品组
        materialInfoRequest.setScItemGroupCode(forecastOrderSDO.getProductGroupCode());


        // 人的信息
        HumanInfoRequest humanInfoRequest = new HumanInfoRequest();
        //客户编码
        humanInfoRequest.setCustomerCode(forecastOrderSDO.getCustomerCode());
        //售达方编码 客户编码（SAP售达方编码）
        humanInfoRequest.setCustomerSaleAddressCode(forecastOrderSDO.getWareHouseCode());
        //
        humanInfoRequest.setCustomerSendAddressCode(forecastOrderSDO.getWareHouseCode());
        //客户收货地址编码（SAP 送达方编码）
        humanInfoRequest.setCustomerSendAddressCode(forecastOrderSDO.getReceiveAddressCode());
        //价目清单编码 (从客户信息上取)
        humanInfoRequest.setCustomerSaleAddressCode(forecastOrderSDO.getCustomerCode());
        Result<List<CustomerSaleScope>> listResult = null;
        try {
            BatchQueryByCustomerCodesRequest customerSales = new BatchQueryByCustomerCodesRequest();
            customerSales.setCustomerCodes(Collections.singletonList(forecastOrderSDO.getCustomerCode()));
            listResult = customerSaleScopeService.batchQueryByCustomerCodes(customerSales);
        } catch (Exception e) {
            log.error("查询客户客户售达方错误,客户编码:" + JSON.toJSONString(forecastOrderSDO.getCustomerCode()));
            e.printStackTrace();
        }
        if (Objects.nonNull(listResult)
                && CollectionUtils.isNotEmpty(listResult.getResult())) {
            CustomerSaleScope customerSaleScope = listResult.getResult().get(0);
            humanInfoRequest.setCustomerGroup(customerSaleScope.getCustomerGroup());
            placeInfoRequest.setSalesArea(customerSaleScope.getSalesArea());
        }
        dimensionPropertyInfoRequest.setMaterialInfoRequest(materialInfoRequest);
        dimensionPropertyInfoRequest.setHumanInfoRequest(humanInfoRequest);
        dimensionPropertyInfoRequest.setPlaceInfoRequest(placeInfoRequest);

        //添加维度
        dimensionPropertyInfoList.add(dimensionPropertyInfoRequest);
        priceQueryRequest.setDimensionPropertyInfoRequestList(dimensionPropertyInfoList);
        Long moneyAmount = 0L;
        log.info("主单ID={},赠品 ID={},查询赠品价格!", forecastOrderSDO.getId(), giftSDO.getScItemId());
        Map<String, String> map = new HashMap<>();
        map.put(CODE_FLAG, INNER_CODE_TO_OUT_CODE);
        priceQueryRequest.setFeatures(map);
        log.info("查询价格入参：", priceQueryRequest);
        Result<PriceQueryResponse> priceQueryResponseResult = priceQueryService.batchQueryPriceExpand(priceQueryRequest);
        if (!priceQueryResponseResult.isSuccess() || priceQueryResponseResult.getResult() == null) {
            return -1L;
        }
        List<ItemPriceResponse> itemPriceResponseList = priceQueryResponseResult.getResult().getItemPriceResponseList();
        ItemPriceResponse itemPriceResponse = itemPriceResponseList.get(0);
        moneyAmount = itemPriceResponse.getMoneyAmout();
        return moneyAmount;
    }
}
